#!/usr/bin/env python
# coding=utf-8

import os
import sys
import time
import anydbm
import zlib


def main():
	if len(sys.argv) == 1:
		return
	if len(sys.argv) > 2:
		num = int(sys.argv[2])
		delFromDb = True
	else:
		num = 50
		delFromDb = False
	dbfn = sys.argv[1]
	pt = os.path.split(os.path.abspath(dbfn))[0]
	dbn = os.path.split(os.path.abspath(dbfn))[1]
	os.chdir(pt)
	db = anydbm.open(dbn, 'w')
	keys = list(db.iterkeys())
	keys.sort()
	keysd = []
	for key in keys:
		try:
			if num <= 0:
				break
			num -= 1
			fn = key + '.bmp'
			f = open(fn, 'wb')
			f.write(zlib.decompress(db[key]))
			f.close()
			keysd.append(key)
		except:
			pass
	if delFromDb:
		for key in keysd:
			del db[key]
	db.close()

if __name__ == '__main__':
	main()

